import axios from "axios";
import { ElMessage, ElMessageBox } from "element-plus";
import router from "@/router/index";
import { decrypt, encrypt } from "@/utils/crypt";
import coolConfirm from "@/utils/coolConfirm";

const API = axios.create({
  // baseURL: "https://contract.ciceseal.com",
  // baseURL: "https://10.41.3.130:1171",
  // baseURL: "http://192.168.2.61:8000",
  baseURL: "/api",
  timeout: 30000,
  headers: {
    "Content-Type": "application/json;charset=utf-8",
  },
});
// 请求拦截
const _encryptRequestWhiteList = [];
API.interceptors.request.use((config) => {
  config.headers = config.headers || {};
  if (localStorage.getItem("token")) {
    config.headers.token = localStorage.getItem("token") || "";
  }
  // if (!_encryptRequestWhiteList.includes(config.url)) {
  //   config.data = { data: encrypt(config.data) };
  // }
  return config;
});
// 响应拦截
let isEndToken = false;
const _InterceptorsWhiteList = [];
API.interceptors.response.use(
  (respose) => {
    if (respose.data.code == 0) {
      ElMessage({
        type: "error",
        message: respose.data.msg,
      });
      return false;
    } else if (respose.data.code == 1) {
      // if (!_InterceptorsWhiteList.includes(respose.config.url)) {
      //   const datas = JSON.parse(decrypt(respose.data.data));
      //   respose.data.data = datas;
      // }
      if (!respose.data.data) {
        return true;
      } else {
        return respose.data.data;
      }
    } else if (respose.data.code == 2) {
      if (!isEndToken) {
        isEndToken = true;
        coolConfirm
          .confirm({
            title: "操作提示",
            message: "当前账号已登录失效，请点击下方重新登录账号",
            confirmButtonText: "重新登录",
            cancelButtonText: "取消",
          })
          .then(() => {
            // 点击确认按钮后的操作
            isEndToken = false;
            router.push("/login");
          })
          .catch(() => {
            // 点击取消按钮或关闭弹窗后的操作
            isEndToken = false;
          });
      }
      return false;
    }
  },
  (err) => {
    ElMessage({ type: "error", message: "服务异常" });
    return Promise.reject(err);
  }
);
export default API;
